import { mongo } from "mongoose";
import { Team, User, TeamMember } from "../schema/index.js";
import { auth } from "./system.js";

export const useTeamRoute = app => {
  // 获取团队列表
  app.get("/teams", auth(), async (req, res) => {
    try {
      const start = parseInt(req.query._start) || 0;
      const end = parseInt(req.query._end) || 20;
      const order = req.query._order === "DESC" ? 1 : -1;
      const sort = req.query._sort || "createTime";
      const name = req.query.name || "";
      const where = {
        ...(name
            ? {
                name: { $regex: name, $options: 'i' }
              }
            : {}),
      };

      const teamsRaw = await Team.find(where)
        .skip(start)
        .limit(end - start)
        .sort({ [sort]: order });

      const teams = [];

      for (const kbRaw of teamsRaw) {
        const team = kbRaw.toObject();

        const orderedTeam = {
          id: team._id.toString(),
          userId: team.ownerId,
          name: team.name,
          createTime: team.createTime,
        };

        teams.push(orderedTeam);
      }

      const totalCount = await Team.countDocuments(where);

      res.header("Access-Control-Expose-Headers", "X-Total-Count");
      res.header("X-Total-Count", totalCount);
      res.json(teams);
    } catch (err) {
      console.log(`Error fetching users: ${err}`);
      res.status(500).json({ error: "Error fetching users" });
    }
  });
  // 创建团队
  app.post('/teams', auth(), async (req, res) => {
    try {
      const { name } = req.body;

      // 找到root用户
      const userInfo = await User.findOne({username: 'root'})
      console.log("root用户ID:", userInfo._id);
      // 新建团队
      const newTeam = await Team.create({
        name,
        ownerId: new mongo.ObjectId(userInfo._id),
      });

      // 将新用户添加到默认团队
      const newTeamMember = await TeamMember.create({
        teamId: newTeam._id,
        userId: userInfo._id,
        role: 'admin',
        status: 'active',
        defaultTeam: true
      });

      res.status(200).json({
        team: newTeam,
        teamMember: newTeamMember
      });

    } catch (err) {
      console.error(`创建用户或团队时出错: ${err}`);
      res.status(500).json({error: '创建用户或团队时出错'});
    }
  });
  // 删除团队
  app.delete('/teams/:id', auth(), async (req, res) => {
    const _id = req.params.id;

    try {
      const team = await Team.findById(_id);

      if (!team) {
        return res.status(404).send('团队不存在');
      }

      // 删除与用户相关联的团队成员信息
      const teamDeleteResult = await TeamMember.deleteMany({teamId:team._id});
      if (teamDeleteResult.deletedCount === 0) {
        console.log(`没有找到或删除任何与团队ID ${_id} 关联的信息`);
      }

      // 删除团队
      await Team.findByIdAndDelete(_id);

      res.send('团队删除成功');
    } catch (error) {
      console.error('删除团队过程中发生错误:', error);
      res.status(500).send('内部服务器错误');
    }
  });

  // 修改团队信息
  app.put('/teams/:id', auth(), async (req, res) => {
    try {
      const _id = req.params.id;

      let { name } = req.body;

      const result = await Team.findByIdAndUpdate(_id, {
        ...(name && {name}),
      });
      res.json(result);
    } catch (err) {
      console.log(`Error updating user: ${err}`);
      res.status(500).json({error: 'Error updating user'});
    }
  });
};
